package com.qianniu.napi.admin.web;

import akka.actor.ActorRef;
import akka.actor.Props;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.admin.service.akka.AkkaServer;
import com.qianniu.napi.admin.service.akka.OrderActor;
import com.qianniu.napi.admin.service.akka.UserActor;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.DateUtil;
import com.qianniu.napi.common.util.EncryptUtil;
import com.qianniu.napi.common.util.ObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * <p>
 * </p>
 *
 * @author chenxuebin
 * @since 2019-03-21
 */
@Controller
public class ShareOpenController {

    private static final Logger logger = LoggerFactory.getLogger(ShareOpenController.class);

    @Autowired
    private IShareOpenService shareopenService;
    @Autowired
    private IShareService shareService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private INewsService newsService;
    @Autowired
    private ICouponTplService couponTplService;
    @Autowired
    private IMerchantService merchantService;
    @Autowired
    private IGoodsQunzfService goodsQunzfService;

    @RequestMapping("/api/shareopen/list")
    @ResponseBody
    public Jinfo list(@RequestParam(value = "status", required = false) String status,
                      @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                      @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        Jinfo info = new Jinfo();
        if (pageSize == null) pageSize = 10;
        Page page = new Page(pageIndex, pageSize);
        page = shareopenService.selectPage(page, new EntityWrapper<ShareOpen>()
                .eq("uid", ObjectUtil.getUid())
                .eq("state", 1));
        info.setInfo(page.getRecords());
        return info;
    }

    @RequestMapping("/api/shareopen/add")
    @ResponseBody
    public Jinfo shareopenAdd(@Valid ShareOpen shareopen,
                              @RequestParam(value = "encryptedData", required = false) String encryptedData,
                              @RequestParam(value = "iv", required = false) String iv,
                              @RequestParam(value = "ori", required = false) String ori,
                              @RequestParam(value = "ma", required = false) String ma,
                              @RequestParam(value = "code", required = false) String code
    ) {
        Jinfo info = new Jinfo();
        // 字段校验
        logger.debug("----------------------------------------------------------------ori=" + ori);
        logger.debug("----------------------------------------------------------------ma=" + ma);
        logger.debug("----------------------------------------------------------------iv=" + iv);
        logger.debug("----------------------------------------------------------------code=" + code);
        logger.debug("----------------------------------------------------------------encryptedData=" + encryptedData);

        String path = ObjectUtil.sortQuery(shareopen.getPath());
        Integer iotype = shareopen.getIotype();

        Map<String, String> pathmap = ObjectUtil.sortQueryMap(shareopen.getPath());
        if (pathmap != null && Strings.isNullOrEmpty(ma) && pathmap.containsKey("ma")) {
            ma = pathmap.get("ma");
        }
        if (Strings.isNullOrEmpty(ori) && pathmap != null && pathmap.containsKey("ori")) {
            ori = pathmap.get("ori");
        }
        logger.debug("----------------------------------------------------------------path=" + path);
        // 添加ts原因是，过滤无转发记录
        if (path.indexOf("?") < 0) {
            Date now = new Date();
            path += "?ts=" + now.getTime();
        }
        logger.debug("----------------------------------------------------------------path=" + path);

        String pathguid = EncryptUtil.md5(path);
        shareopen.setPath(path);
        shareopen.setPathguid(pathguid);
        logger.debug("----------------------------------------------------------------shareopen.path=" + shareopen.getPath());

        shareopen.setCreateday(DateUtil.getToday());
        shareopen.setCreatetime(new Date());
        shareopen.setUid(ObjectUtil.getUid());
        shareopen.setMid(ObjectUtil.getMid());
        shareopen.setMpid(ObjectUtil.getMpid());
        shareopen.setGuid(ObjectUtil.getGuid());
        shareopen.setShareday(DateUtil.getToday());
        Long ywid = null;

        if (!Strings.isNullOrEmpty(ma)) {
            ori = ma;// 海报扫码优先级高
            shareopen.setOri(ma);
//            String ma[scene]= uid + "_" + Constants.PAGE_MAP.get(page) + "_Q_" + ywid;
            Long uid = null;
            String[] oris = ori.split("_");
            if (oris.length == 4) {
                try {
                    uid = Long.valueOf(oris[0]);
                    ywid = Long.valueOf(oris[3]);
                } catch (Exception e) {
                    logger.error("======shareopenAdd parse uid error", e);
                }
            }
            shareopen.setZuid(uid);
            User zuser = userService.selectById(uid);
            if (zuser != null) {
                shareopen.setZguid(zuser.getGuid());
            }
        } else if (!Strings.isNullOrEmpty(ori)) {
            shareopen.setOri(ori);
            shareopen.setZguid(ori.split("_")[0]);
            String[] oris = ori.split("_");
            ywid = Strings.isNullOrEmpty(oris[3]) ? null : Long.valueOf(oris[3]);

            User zuser = redisService.getUserByGuid(shareopen.getZguid());
            if (zuser != null) {
                shareopen.setZuid(zuser.getId());
            }
            User user = redisService.getUserByGuid(shareopen.getGuid());
            if (user != null) {
                shareopen.setOpenid(user.getOpenid());
            }
        }
        shareopen.setYwid(ywid);

        Goods goods = goodsService.selectOne(new EntityWrapper<Goods>().setSqlSelect("id,sharenum,sid,leagueid").eq("id", ywid));
        CouponTpl ctpl = couponTplService.selectOne(new EntityWrapper<CouponTpl>().setSqlSelect("id,sid,leagueid").eq("id", ywid));

        Long sid = null;
        Long leagueid = null;
        if (goods != null) {
            sid = goods.getSid();
            leagueid = goods.getLeagueid();
            goods.setSharenum(goods.getSharenum() + 1);
        } else if (ctpl != null) {
            sid = ctpl.getSid();
            leagueid = ctpl.getLeagueid();
        }
        if (sid != null && sid.intValue() == 0) sid = null;
        shareopen.setSid(sid);
        shareopen.setLeagueid(leagueid);

        // 转发必须带参数，如无[ts=timestamp]
        Share share = shareService.selectOne(new EntityWrapper<Share>().eq("pathguid", pathguid));
//        GoodsQunzf goodsQunzf = share != null && share.getYwid() != null ? goodsQunzfService.selectById(share.getYwid()) : null;
        GoodsQunzf goodsQunzf = ywid != null ? goodsQunzfService.selectById(ywid) : null;

        if (share != null) {
            shareopen.setShareid(share.getId());

            ShareOpen nshareopen = new ShareOpen();
            nshareopen.setShareid(share.getId());//========1、更新同分享路径shareid========

            if (share.getGroupid() == null) {
                JSONObject json = Strings.isNullOrEmpty(iv)? null : ObjectUtil.wxdectypt(encryptedData, iv, code, null);
                logger.debug("----------------------------------------------------------------------------wxdectypt json=" + JSONObject.toJSONString(json));
                if (json != null) share.setGroupid(json.getString("openGId"));
            } else {
                nshareopen.setGroupid(share.getGroupid());//========2、更新同分享路径groupid========
            }
            shareopen.setGroupid(share.getGroupid());

            shareopenService.update(nshareopen, new EntityWrapper<ShareOpen>().eq("pathguid", pathguid));

            if (!Strings.isNullOrEmpty(share.getGroupid())) {
                //一个商品对一个用户一个群只有一次奖励【系统默认】
                Wrapper<Share> wrapper = new EntityWrapper<Share>()
                        .eq("groupid", share.getYwid())
                        .eq("ywid", share.getYwid())
                        .eq("uid", share.getUid())
                        .eq("sendoff", 1);

                int sendoffcout = shareService.selectCount(wrapper);
                share.setQfjiang(goodsQunzf == null || goodsQunzf.getState() != 1 || sendoffcout > 0 ? -1 : 1);
            }
            share.setViews(share.getViews() + 1);
            share.updateById();

            shareopen.setZguid(share.getGuid());
            shareopen.setZuid(share.getUid());
        }

        // 新用户则，存储当前用户所在OEM品牌
        int cout = shareopenService.selectCount(new EntityWrapper<ShareOpen>().eq("guid", shareopen.getGuid()));
        if (cout == 0 && shareopen.getZuid() != null) {
            User zuser = userService.selectById(shareopen.getZuid());
            User zoemuser = null;
            if (!Strings.isNullOrEmpty(zuser.getPhone())) {
                zoemuser = userService.selectOne(new EntityWrapper<User>()
                        .setSqlSelect("id,mid")
                        .eq("phone", zuser.getPhone())
                        .eq("is_oem", 1));
            }
            if (zoemuser != null) {
                Merchant merchant = merchantService.selectById(zoemuser.getMid());
                String rkey = Constants.REDIS_OEM + shareopen.getMpid() + "_" + shareopen.getGuid();
                redisService.set(rkey, merchant.getZcname(), 10, TimeUnit.MINUTES);//保存redis

                Oem oem = new Oem();
                oem.setPguid(shareopen.getZguid());
                oem.setGuid(shareopen.getGuid());
                oem.setOem(merchant.getZcname());
                oem.setOemid(merchant.getId());
                oem.setCreatetime(new Date());
                oem.insert();//保存入库
            }
        }

        cout = shareopenService.selectCount(new EntityWrapper<ShareOpen>().eq("guid", shareopen.getGuid()).eq("pathguid", shareopen.getPathguid()));
        shareopen.setIsnew(cout == 0 ? 1 : -1);// 首次打开该分享
        shareopen.insert();

        Share nshare = new Share();
        if (share != null) {
            List<ShareOpen> shareOpenlist = shareopenService.selectList(new EntityWrapper<ShareOpen>().setSqlSelect(" distinct guid as guid")
                    .eq("pathguid", pathguid).eq("mpid", shareopen.getMpid()));

            nshare.setViewusers(shareOpenlist.size());
            nshare.setId(share.getId());
            nshare.updateById();
        }

        //群转发奖励佣金
        //触发条件：设置群发奖励+进入打开页面
        if (share != null && share.getQfjiang() != null && share.getQfjiang() == 1 && (iotype == 1 || iotype == null)) {
            logger.debug("---------------------------------------------------------------share.getQfjiang()==1");

            logger.debug("---------------------------------------------------------------nshare.getViewusers()=" + nshare.getViewusers());
            if (goodsQunzf != null)
                logger.debug("-----------------------------------------------------------goodsQunzf.getMinDianji()=" + goodsQunzf.getMinDianji());
            if (goodsQunzf != null && nshare.getViewusers().intValue() == goodsQunzf.getMinDianji().intValue()) {
                AkkaServer.system.actorOf(Props.create(OrderActor.class))
                        .tell(Constants.AKKA_MSG_ORDER_QUNZHUANFA + "@" + share.getId(), ActorRef.noSender());
            }
        }

        // 处理群转发&已登录认证的用户&&且有转发实际商品活动
        // shareopen.getScene() == 1007 单人聊天会话中的小程序消息卡片
        // shareopen.getScene() == 1008 群聊会话中的小程序消息卡片
        // shareopen.getScene() == 1044 1044: 带 shareTicket 的小程序消息卡片
        // shareopen.getScene() == 1044 1047: 扫描小程序码
        // shareopen.getScene() == 1048 1048: 长按图片识别小程序码
        // shareopen.getScene() == 1049 1049: 手机相册选取小程序码
        // if (shareopen.getScene() == 1044 && share == null && ywid != null

        // 不管任何渠道，都记录所有转发记录并统计
        if ((shareopen.getScene() == 1007 || shareopen.getScene() == 1008 || shareopen.getScene() == 1044 || shareopen.getScene() == 1047
                || shareopen.getScene() == 1048 || shareopen.getScene() == 1049)
                && share == null && ywid != null
                && shareopen.getZuid() != null && ywid > 0) {

            share = new Share();

            User user = userService.selectById(shareopen.getZuid());
            share.setNickname(user.getNickName());
            share.setAvatarpic(user.getAvatarPic());
            if (shareopen.getScene() == 1044 && pathmap.containsKey("ts")) {
                try {
                    Date sharedate = new Date(new Long(pathmap.get("ts")));
                    share.setSharedate(DateUtil.getToday(sharedate));
                } catch (Exception e) {
                    logger.error("------------sharedate parse error for ts=" + pathmap.get("ts"), e);
                }
            }

            share.setPath(path);
            share.setPathguid(pathguid);

            String page = path.substring(0, path.indexOf("?"));
            share.setPage(page);
            share.setViewusers(1);
            share.setViews((iotype == null || iotype == 1) ? 1 : 0);
            share.setBuys(0);
            share.setRegists(0);
            share.setCreatetime(new Date());

            share.setGuid(user.getGuid());
            share.setUid(shareopen.getZuid());
            share.setMid(ObjectUtil.getMid());
            share.setMpid(ObjectUtil.getMpid());

            share.setSid(sid);
            share.setLeagueid(leagueid);

            share.setYwid(ywid);

            share.setQfjiang(goodsQunzf == null || goodsQunzf.getState() != 1 ? null : 1);

            share.insert();

            ShareOpen nshareopen = new ShareOpen();
            nshareopen.setId(shareopen.getId());
            nshareopen.setShareid(share.getId());
            nshareopen.updateById();

            if (goods != null) {
                goods.setModifytime(new Date());
                goods.updateById();
            }
        }

        if (ywid != null) {
            News news = newsService.selectById(ywid);
            if ((path.indexOf("/qntsp") > 0 || path.indexOf("/newsdetail") > 0) && news != null) {
                News nnews = new News();
                nnews.setSharecout(news.getSharecout() == null ? 1 : news.getSharecout() + 1);
                nnews.setModifytime(new Date());
                nnews.setId(news.getId());
                nnews.updateById();
            }
        }

        if (shareopen.getZuid() != null) {
            AkkaServer.system.actorOf(Props.create(UserActor.class))
                    .tell(Constants.AKKA_MSG_SHARE_OPEN + "@" + shareopen.getId(), ActorRef.noSender());
        }

        return info;
    }

    @RequestMapping("/api/shareopen/leave")
    @ResponseBody
    public Jinfo shareopenAddLeave(@Valid ShareOpen shareopen,
                                   @RequestParam(value = "ori", required = false) String ori,
                                   @RequestParam(value = "ma", required = false) String ma
    ) {
        Jinfo info = new Jinfo();

        // 字段校验
        logger.debug("----------------------------------------------------------------ori=" + ori);
        logger.debug("----------------------------------------------------------------ma=" + ma);

        String path = ObjectUtil.sortQuery(shareopen.getPath());
        Map<String, String> pathmap = ObjectUtil.sortQueryMap(shareopen.getPath());
        if (pathmap != null && Strings.isNullOrEmpty(ma) && pathmap.containsKey("ma")) {
            ma = pathmap.get("ma");
        }
        if (Strings.isNullOrEmpty(ori) && pathmap != null && pathmap.containsKey("ori")) {
            ori = pathmap.get("ori");
        }

        logger.debug("----------------------------------------------------------------path=" + path);
        // 添加ts原因是，过滤无转发记录
        if (path.indexOf("?") < 0) {
            Date now = new Date();
            path += "?ts=" + now.getTime();
        }
        logger.debug("----------------------------------------------------------------path=" + path);

        String pathguid = EncryptUtil.md5(path);
        shareopen.setPath(path);
        shareopen.setPathguid(pathguid);
        logger.debug("----------------------------------------------------------------shareopen.path=" + shareopen.getPath());

        shareopen.setCreateday(DateUtil.getToday());
        shareopen.setCreatetime(new Date());
        shareopen.setUid(ObjectUtil.getUid());
        shareopen.setMid(ObjectUtil.getMid());
        shareopen.setMpid(ObjectUtil.getMpid());
        shareopen.setGuid(ObjectUtil.getGuid());
        shareopen.setShareday(DateUtil.getToday());
        Long ywid = null;

        if (!Strings.isNullOrEmpty(ma)) {
            ori = ma;// 海报扫码优先级高
            shareopen.setOri(ma);
//            String ma[scene]= uid + "_" + Constants.PAGE_MAP.get(page) + "_Q_" + ywid;
            Long uid = null;
            String[] oris = ori.split("_");
            if (oris.length == 4) {
                try {
                    uid = Long.valueOf(oris[0]);
                    ywid = Long.valueOf(oris[3]);
                } catch (Exception e) {
                    logger.error("======shareopenAdd parse uid error", e);
                }
            }
            shareopen.setZuid(uid);
            User zuser = userService.selectById(uid);
            if (zuser != null) {
                shareopen.setZguid(zuser.getGuid());
            }
        } else if (!Strings.isNullOrEmpty(ori)) {
            shareopen.setOri(ori);
            shareopen.setZguid(ori.split("_")[0]);
            String[] oris = ori.split("_");
            ywid = Strings.isNullOrEmpty(oris[3]) ? null : Long.valueOf(oris[3]);

            User zuser = redisService.getUserByGuid(shareopen.getZguid());
            if (zuser != null) {
                shareopen.setZuid(zuser.getId());
            }
            User user = redisService.getUserByGuid(shareopen.getGuid());
            if (user != null) {
                shareopen.setOpenid(user.getOpenid());
            }
        }
        shareopen.setYwid(ywid);
        Long sid = null;
        Long leagueid = null;

        if (ywid != null) {
            Goods goods = goodsService.selectOne(new EntityWrapper<Goods>().setSqlSelect("id,sharenum,sid,leagueid").eq("id", ywid));
            CouponTpl ctpl = couponTplService.selectOne(new EntityWrapper<CouponTpl>().setSqlSelect("id,sid,leagueid").eq("id", ywid));
            News news = newsService.selectOne(new EntityWrapper<News>().setSqlSelect("id,sid,leagueid").eq("id", ywid));

            if (goods != null) {
                sid = goods.getSid();
                leagueid = goods.getLeagueid();
            } else if (ctpl != null) {
                sid = ctpl.getSid();
                leagueid = ctpl.getLeagueid();
            } else if (news != null) {
                sid = news.getSid();
                leagueid = news.getLeagueid();
            }
        }

        if (sid != null && sid.intValue() == 0) sid = null;
        shareopen.setSid(sid);
        shareopen.setLeagueid(leagueid);

        //转发必须带参数，如无[ts=timestamp]
        Share share = shareService.selectOne(new EntityWrapper<Share>().eq("pathguid", pathguid));

        if (share != null) {
            shareopen.setShareid(share.getId());

            ShareOpen nshareopen = new ShareOpen();
            //========1、更新同分享路径shareid========
            nshareopen.setShareid(share.getId());
            shareopen.setGroupid(share.getGroupid());
            shareopen.setZguid(share.getGuid());
            shareopen.setZuid(share.getUid());
        }

        shareopen.setIsnew(-1);

        ShareOpen so = shareopenService.selectOne(new EntityWrapper<ShareOpen>().eq("md5", shareopen.getMd5()));
        if (so != null) {
            long timelong = (shareopen.getVisitstamp() - so.getVisitstamp()) / 1000;
            shareopen.setTimelong(timelong);
        }
        shareopen.insert();

        return info;
    }

    @RequestMapping("/api/shareopen/modify")
    @ResponseBody
    public Jinfo shareopenUpdate(HttpServletRequest req,
                                 ShareOpen shareopen) {
        Jinfo info = new Jinfo();
        shareopen.updateById();
        return info;
    }

    @RequestMapping("/api/shareopen/detail")
    @ResponseBody
    public Jinfo getShareOpenDetailById(@RequestParam("token") String token,
                                        @RequestParam("id") long id, HttpServletRequest req
    ) {
        Jinfo info = new Jinfo();
        ShareOpen shareopen = shareopenService.selectById(id);
        info.setInfo(shareopen);
        return info;
    }
}
